<template>
  <div class="letter">
      <div
        class="letter-list"
        @click="handleLetterClick"
        v-for="item of letters"
        :key="item"
        :ref="item"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
      >
      {{item}}</div>
  </div>
</template>

<script>
export default {
  props: {
    citylist: Object
  },
  name: 'CityAlphabet',
  data() {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  updated() {
    this.startY = this.$refs['A'][0].offsetTop
  },
  computed: {
    letters() {
      const letters = []
      for (const i in this.citylist) {
        letters.push(i)
      }
      return letters
    }
  },
  methods: {
    handleLetterClick(e) {
      this.$emit('change', e.target.innerText)
    },
    /* 鼠标移动开始时触发的事件 */
    handleTouchStart() {
      this.touchStatus = true
    },
    /* 鼠标移动过程中触发的事件 */
    handleTouchMove(e) {
      /* 函数节流--防止多次触发 */
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 70
          const index = Math.floor((touchY - this.startY) / 20)
          if (index >= 0 && index <= this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    handleTouchEnd() {
      this.touchStatus = false
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/varibles.styl'
   .letter
     position absolute
     z-index 10
     top 1.4rem
     right 0
     bottom 0
     width .4rem
     display flex
     flex-direction column
     justify-content center
     .letter-list
        height .4rem
        line-height .44rem
        text-align center
        color $bgColor
</style>
